package com.wzxy.views;

import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.servlet.view.document.AbstractExcelView;

import com.wzxy.model.Department;
import com.wzxy.utils.ExcelUtil;

/**
 * 创建部门的 excel
 * @author h
 *
 */
public class ViewExcel extends AbstractExcelView {

	@Override
	protected void buildExcelDocument(Map<String, Object> model, HSSFWorkbook workbook, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// map的key，在对应的controller中设置
		@SuppressWarnings("unchecked")
		List<Department> list = (List<Department>) model.get("list");
		HSSFSheet sheet = workbook.createSheet("list"); //创建sheet的名称
		//sheet.setDefaultColumnWidth((short) 12);
		
		//设置自动调整列宽
		sheet.autoSizeColumn((short)0);
		sheet.autoSizeColumn((short)1);
		sheet.autoSizeColumn((short)2);
		
		HSSFCell cell = getCell(sheet, 0, 0);
		setText(cell, "部门编号");
		cell = getCell(sheet, 0, 1);
		setText(cell, "部门名称");
		cell = getCell(sheet, 0, 2);
		setText(cell, "部门描述");

		for (short i = 0; i < list.size(); i++) {
			HSSFRow sheetRow = sheet.createRow(i + 1);
			Department department = list.get(i);
			sheetRow.createCell(0).setCellValue(department.getDid());
			sheetRow.createCell(1).setCellValue(department.getDname());
			sheetRow.createCell(2).setCellValue(department.getDdesc());
		}
		// 设置下载时客户端Excel的名称
		String filename ="department-"+ new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + ".xls";
		// 处理中文文件名
		filename = ExcelUtil.encodeFilename(filename, request);
		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-disposition", "attachment;filename=" + filename);
		OutputStream ouputStream = response.getOutputStream();
		workbook.write(ouputStream);
		ouputStream.flush();
		ouputStream.close();
	}
}